/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
import store from '@/config/store/';
import router from '@/config/router/'
import { serialize } from '@/utils/util'
import { ElMessage } from 'element-plus'
import website from '@/config/website';
import NProgress from '@/config/nprogress/index.js'
axios.defaults.timeout = 10000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start() // 开启进度条
   const isToken = (config.headers || {}).isToken === false
   const token = store.getters.token
   if (token && !isToken) {
    config.headers['Authorization'] = 'Bearer ' + token// token
   }

  const meta = (config.meta || {});  
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  return config
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.close()
  const status = Number(res.status) || 200;
  const statusWhiteList = website.statusWhiteList || [];
  const message = res.data.message || '未知错误';
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  //后台定义 424 针对令牌过期的特殊响应码
  if (status === 424) store.dispatch('LogOut').then(() => router.push({ path: '/login' }));
  // 如果请求为非200否者默认统一处理
  if (status !== 200) {
    // ElMessage({
    //   message: message,
    //   type: 'error'
    // })
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.close()
  return Promise.reject(new Error(error));
})

export default axios;